#!/bin/bash

# 启用严格错误检查
set -e
set -o pipefail

# 日志函数
log() {
    echo "[$(date --iso-8601=seconds)] $1"
}

log "=== 开始发布流程 ==="

# 检查是否由标签触发
if [ -z "$CI_COMMIT_TAG" ]; then
    log "错误：此任务必须由Git标签触发。"
    exit 1
fi

# 定义变量
TAG_NAME="$CI_COMMIT_TAG"
ARCHIVE_NAME="release-${TAG_NAME}.zip"
API_URL="$CI_API_V4_URL"
PACKAGE_NAME="source_code"

# 打包源代码
log "正在打包源代码 (${TAG_NAME})..."
git archive --format zip --output "${ARCHIVE_NAME}" HEAD
if [ ! -f "${ARCHIVE_NAME}" ]; then
    log "错误：源代码打包失败！"
    exit 1
fi
log "已生成压缩包：${ARCHIVE_NAME}"

# 上传到Generic Packages
log "正在上传到Generic Packages..."
UPLOAD_URL="${API_URL}/projects/${CI_PROJECT_ID}/packages/generic/${PACKAGE_NAME}/${TAG_NAME}/${ARCHIVE_NAME}"
log "UPLOAD_URL: ${UPLOAD_URL}"
curl_response=$(curl --silent --show-error --fail \
    --header "PRIVATE-TOKEN: ${API_TOKEN}" \
    --upload-file "${ARCHIVE_NAME}" \
    "${UPLOAD_URL}")
log "上传成功。响应：${curl_response}"

# 构建Release描述
RELEASE_DESC="自动化发布 ${TAG_NAME}\n\n包含以下资源：\n- 完整源代码包"

# 创建Release
log "正在创建GitLab Release..."
release_payload=$(cat <<EOF
{
  "name": "Release ${TAG_NAME}",
  "tag_name": "${TAG_NAME}",
  "description": "${RELEASE_DESC}",
  "assets": {
    "links": [
      {
        "name": "源代码",
        "url": "${UPLOAD_URL}",
        "link_type": "package"
      }
    ]
  }
}
EOF
)

create_response=$(curl --silent --show-error --fail \
    --header "Content-Type: application/json" \
    --header "PRIVATE-TOKEN: ${API_TOKEN}" \
    --data "${release_payload}" \
    "${API_URL}/projects/${CI_PROJECT_ID}/releases")

log "Release创建成功！响应：${create_response}"
log "=== 发布流程完成 ==="
